#!/bin/bash

# 创建发布目录
mkdir -p dist

# 清理旧的发布文件
rm -rf dist/*

# 复制必要文件
cp -r \
    manifest.json \
    background.js \
    popup.html \
    popup.js \
    images \
    LICENSE \
    LICENSE.zh-CN \
    README.md \
    README.en.md \
    dist/

# 生成密钥（如果不存在）
if [ ! -f "./dist/private.pem" ]; then
    openssl genrsa -out "./dist/private.pem" 2048
    echo "生成新的私钥文件"
fi

# 打包为zip文件
cd dist
zip -r auto-rewards.zip *
cd ..

# 使用 Chrome 命令行打包 crx
# 注意：需要设置 CHROME_PATH 为你的 Chrome 可执行文件路径
if [ -z "$CHROME_PATH" ]; then
    # 尝试常见的 Chrome 路径
    if [ -f "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" ]; then
        CHROME_PATH="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
    elif [ -f "/usr/bin/google-chrome" ]; then
        CHROME_PATH="/usr/bin/google-chrome"
    elif [ -f "/usr/bin/chromium" ]; then
        CHROME_PATH="/usr/bin/chromium"
    elif [ -f "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe" ]; then
        CHROME_PATH="C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"
    else
        echo "错误: 未找到 Chrome 浏览器，请设置 CHROME_PATH 环境变量"
        exit 1
    fi
fi

# 打包为 crx
"$CHROME_PATH" --pack-extension="./dist" --pack-extension-key="./dist/private.pem"

# 移动生成的 crx 文件
mv dist.crx dist/auto-rewards.crx

echo "打包完成，文件位于:"
echo "- ZIP文件: dist/auto-rewards.zip"
echo "- CRX文件: dist/auto-rewards.crx"
echo "- 密钥文件: dist/private.pem (请妥善保管)"